//
//  PostFarmViewController.m
//  PeopleStreet
//
//  Created by 刘建峰 on 16/6/27.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "PostFarmViewController.h"
#import "UICustomActionSheet.h"
#import "UIImagePickerController+Edit.h"
#import "PhotoPopView.h"

@interface PostFarmViewController ()<UIActionSheetDelegate,
UITextViewDelegate>
@property (weak, nonatomic) IBOutlet UIView *navView;
@property (weak, nonatomic) IBOutlet UIScrollView *scroView;
@property (weak, nonatomic) IBOutlet UIImageView *photoImage;
@property (weak, nonatomic) IBOutlet UIButton *photoButton;
@property (weak, nonatomic) IBOutlet UILabel *placeHolder;
@property (weak, nonatomic) IBOutlet UITextView *textView;
@property (weak, nonatomic) IBOutlet UITextField *titleLabel;
@property (weak, nonatomic) IBOutlet UITextField *numLabel;
@property (weak, nonatomic) IBOutlet UITextField *specifyLabel;
@property (weak, nonatomic) IBOutlet UITextField *phoneLabel;
@property (weak, nonatomic) IBOutlet UIButton *commitButton;
@property (copy, nonatomic) NSString *imageStr;
@property (nonatomic,strong) NSMutableArray * images;
@property (weak, nonatomic) IBOutlet UIScrollView *photoScroView;

@end

@implementation PostFarmViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _images = [NSMutableArray array];
    _imageStr = @"";

    [self initViewLayout];
}

- (void)initViewLayout{
    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.navView];
    [self adaptiveViewLayout:self.scroView];
    [self adaptiveViewLayout:self.photoScroView];
    _scroView.contentSize = flexibleSize(CGSizeMake(0, 505), NO);
    _commitButton.layer.masksToBounds = YES;
    _commitButton.layer.cornerRadius = 20*VerticalRatio();
    
    _textView.delegate = self;
}

- (IBAction)back:(id)sender {
    [self.navigationController  popViewControllerAnimated:YES];
}


#pragma mark  ==== 确认发布
- (IBAction)sureCommit:(id)sender {
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    if ([Common dataIsNULL:_titleLabel.text]) {
        [CWHUDTips showTips:@"请输入标题"];
        return;
    }
    if ([Common dataIsNULL:_numLabel.text]) {
        [CWHUDTips showTips:@"请输入数量"];
        return;
    }
    if ([Common dataIsNULL:_specifyLabel.text]) {
        [CWHUDTips showTips:@"请输入单位"];
        return;
    }
    if ([Common dataIsNULL:_phoneLabel.text]) {
        [CWHUDTips showTips:@"请输入联系电话"];
        return;
    }
    
    [dic setObject:_titleLabel.text forKey:@"mmsuName"];
    [dic setObject:_numLabel.text forKey:@"mmsuNum"];
    [dic setObject:_specifyLabel.text forKey:@"mmsuLabel"];
    [dic setObject:_textView.text forKey:@"mmsuContent"];
    [dic setObject:_phoneLabel.text forKey:@"mmsuPhone"];

    for (int i = 0; i<_images.count; i++) {
        NSString * image = _images[i];
        if (i!=0) {
            image = [NSString stringWithFormat:@",%@",image];
        }
        _imageStr = [_imageStr stringByAppendingString:image];
    }
    
    [dic setObject:self.imageStr forKey:@"imageStr"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:SX_appAddMarketSupply withHttpType:@"POST" withTag:SX_SX_appAddMarketSupply];
}


#pragma mark ==== textViewDelegate
- (void)textViewDidChange:(UITextView *)textView{
    if (textView  == _textView ) {
        if (_textView.text.length>0) {
            _placeHolder.hidden = YES;
        }else{
            _placeHolder.hidden = NO;
        }
    }
}

#pragma mark - 选择照片
- (IBAction)PublishImage:(id)sender {
    if (_images.count==5) {
        UIAlertView * alertView =[[UIAlertView alloc]initWithTitle:@"提示" message:@"最多只能上传5张照片" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alertView show];
        return;
    }

    PhotoPopView * photoPopView = [[PhotoPopView alloc]initWithcomplect:^(NSInteger index) {
        if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
            UIImagePickerController *controller = [[UIImagePickerController alloc] init];
            __weak __typeof(self)weakSelf = self;
            if (index == 0){
                controller.allowsEditing = YES;
                controller.sourceType = UIImagePickerControllerSourceTypeCamera;
                controller.cropMode = DZNPhotoEditorViewControllerCropModeSquare;
                
                controller.finalizationBlock = ^(UIImagePickerController *picker, NSDictionary *info) {
                    
                    UIImage *image = info[UIImagePickerControllerEditedImage];
                    UIImageView * imageView = [[UIImageView alloc]initWithFrame:flexibleFrame(CGRectMake(13+_images.count*70, 12, 65, 65), NO)];
                    imageView.image = image;
                    [_photoScroView addSubview: imageView];
                    
                    _photoButton.frame = flexibleFrame(CGRectMake(13+(_images.count+1)*70, 12, 65, 55), NO);
                    _photoImage.frame = flexibleFrame(CGRectMake(13+(_images.count+1)*70, 12, 65, 65), NO);
                    if (CGRectGetMaxX(_photoButton.frame)>CGRectGetWidth(self.view.bounds)) {
                        _photoScroView.contentSize = CGSizeMake(CGRectGetMaxX(_photoButton.frame)+13*VerticalRatio(), 0);
                        [_photoScroView setContentOffset:CGPointMake(_photoScroView.contentSize.width-CGRectGetWidth(self.view.bounds), 0) animated:YES];
                    }
                    [self imageUpload:1 :image];
                    // Dismiss when the crop mode was disabled
                    if (picker.cropMode == DZNPhotoEditorViewControllerCropModeNone) {
                        [weakSelf dismissViewControllerAnimated:NO completion:^{
                        }];
                    }
                };
                
                controller.cancellationBlock = ^(UIImagePickerController *picker) {
                    
                    // Dismiss when the crop mode was disabled or if the navigation stack has only one child view controller.
                    if (picker.cropMode == DZNPhotoEditorViewControllerCropModeNone || picker.viewControllers.count == 1) {
                        [weakSelf dismissViewControllerAnimated:NO completion:^{
                        }];
                    }
                    else {
                        picker.cropMode = DZNPhotoEditorViewControllerCropModeSquare;
                        [picker popViewControllerAnimated:YES];
                    }
                };
                [self presentViewController:controller animated:NO completion:^{}];
            }else if (index == 1){
                controller.allowsEditing = YES;
                controller.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                controller.cropMode = DZNPhotoEditorViewControllerCropModeSquare;
                
                controller.finalizationBlock = ^(UIImagePickerController *picker, NSDictionary *info) {
                    
                    UIImage *image = info[UIImagePickerControllerEditedImage];
                    UIImageView * imageView = [[UIImageView alloc]initWithFrame:flexibleFrame(CGRectMake(13+_images.count*70, 12, 65, 65), NO)];
                    imageView.image = image;
                    [_photoScroView addSubview: imageView];
                    
                    _photoButton.frame = flexibleFrame(CGRectMake(13+(_images.count+1)*70, 12, 65, 55), NO);
                    _photoImage.frame = flexibleFrame(CGRectMake(13+(_images.count+1)*70, 12, 65, 65), NO);
                    if (CGRectGetMaxX(_photoButton.frame)>CGRectGetWidth(self.view.bounds)) {
                        _photoScroView.contentSize = CGSizeMake(CGRectGetMaxX(_photoButton.frame)+13*VerticalRatio(), 0);
                        [_photoScroView setContentOffset:CGPointMake(_photoScroView.contentSize.width-CGRectGetWidth(self.view.bounds), 0) animated:YES];
                    }
                    [self imageUpload:1 :image];
                    // Dismiss when the crop mode was disabled
                    if (picker.cropMode == DZNPhotoEditorViewControllerCropModeNone) {
                        [weakSelf dismissViewControllerAnimated:NO completion:^{
                        }];
                    }
                };
                
                controller.cancellationBlock = ^(UIImagePickerController *picker) {
                    
                    // Dismiss when the crop mode was disabled or if the navigation stack has only one child view controller.
                    if (picker.cropMode == DZNPhotoEditorViewControllerCropModeNone || picker.viewControllers.count == 1) {
                        [weakSelf dismissViewControllerAnimated:NO completion:^{
                        }];
                    }
                    else {
                        picker.cropMode = DZNPhotoEditorViewControllerCropModeSquare;
                        [picker popViewControllerAnimated:YES];
                    }
                };
                [self presentViewController:controller animated:NO completion:^{}];
            }
            
            
            
            
        }else {
            UIImagePickerController *controller = [[UIImagePickerController alloc] init];
            __weak __typeof(self)weakSelf = self;
            if (index == 0){
                controller.allowsEditing = YES;
                controller.sourceType = UIImagePickerControllerSourceTypeCamera;
                controller.cropMode = DZNPhotoEditorViewControllerCropModeSquare;
                
                controller.finalizationBlock = ^(UIImagePickerController *picker, NSDictionary *info) {
                    
                    UIImage *image = info[UIImagePickerControllerEditedImage];
                    UIImageView * imageView = [[UIImageView alloc]initWithFrame:flexibleFrame(CGRectMake(13+_images.count*70, 12, 65, 65), NO)];
                    imageView.image = image;
                    [_photoScroView addSubview: imageView];
                    
                    _photoButton.frame = flexibleFrame(CGRectMake(13+(_images.count+1)*70, 12, 65, 55), NO);
                    _photoImage.frame = flexibleFrame(CGRectMake(13+(_images.count+1)*70, 12, 65, 65), NO);
                    if (CGRectGetMaxX(_photoButton.frame)>CGRectGetWidth(self.view.bounds)) {
                        _photoScroView.contentSize = CGSizeMake(CGRectGetMaxX(_photoButton.frame)+13*VerticalRatio(), 0);
                        [_photoScroView setContentOffset:CGPointMake(_photoScroView.contentSize.width-CGRectGetWidth(self.view.bounds), 0) animated:YES];
                    }
                    [self imageUpload:1 :image];
                    // Dismiss when the crop mode was disabled
                    if (picker.cropMode == DZNPhotoEditorViewControllerCropModeNone) {
                        [weakSelf dismissViewControllerAnimated:NO completion:^{
                        }];
                    }
                };
                
                controller.cancellationBlock = ^(UIImagePickerController *picker) {
                    
                    // Dismiss when the crop mode was disabled or if the navigation stack has only one child view controller.
                    if (picker.cropMode == DZNPhotoEditorViewControllerCropModeNone || picker.viewControllers.count == 1) {
                        [weakSelf dismissViewControllerAnimated:NO completion:^{
                        }];
                    }
                    else {
                        picker.cropMode = DZNPhotoEditorViewControllerCropModeSquare;
                        [picker popViewControllerAnimated:YES];
                    }
                };
                [self presentViewController:controller animated:NO completion:^{}];
            }else if (index == 1){
                controller.allowsEditing = YES;
                controller.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                controller.cropMode = DZNPhotoEditorViewControllerCropModeSquare;
                
                controller.finalizationBlock = ^(UIImagePickerController *picker, NSDictionary *info) {
                    
                    UIImage *image = info[UIImagePickerControllerEditedImage];
                    UIImageView * imageView = [[UIImageView alloc]initWithFrame:flexibleFrame(CGRectMake(13+_images.count*70, 12, 65, 65), NO)];
                    imageView.image = image;
                    [_photoScroView addSubview: imageView];
                    
                    _photoButton.frame = flexibleFrame(CGRectMake(13+(_images.count+1)*70, 12, 65, 55), NO);
                    _photoImage.frame = flexibleFrame(CGRectMake(13+(_images.count+1)*70, 12, 65, 65), NO);
                    if (CGRectGetMaxX(_photoButton.frame)>CGRectGetWidth(self.view.bounds)) {
                        _photoScroView.contentSize = CGSizeMake(CGRectGetMaxX(_photoButton.frame)+13*VerticalRatio(), 0);
                        [_photoScroView setContentOffset:CGPointMake(_photoScroView.contentSize.width-CGRectGetWidth(self.view.bounds), 0) animated:YES];
                    }
                    [self imageUpload:1 :image];
                    // Dismiss when the crop mode was disabled
                    if (picker.cropMode == DZNPhotoEditorViewControllerCropModeNone) {
                        [weakSelf dismissViewControllerAnimated:NO completion:^{
                        }];
                    }
                };
                
                controller.cancellationBlock = ^(UIImagePickerController *picker) {
                    
                    // Dismiss when the crop mode was disabled or if the navigation stack has only one child view controller.
                    if (picker.cropMode == DZNPhotoEditorViewControllerCropModeNone || picker.viewControllers.count == 1) {
                        [weakSelf dismissViewControllerAnimated:NO completion:^{
                        }];
                    }
                    else {
                        picker.cropMode = DZNPhotoEditorViewControllerCropModeSquare;
                        [picker popViewControllerAnimated:YES];
                    }
                };
                [self presentViewController:controller animated:NO completion:^{}];
            }
            
        }
        
    }];
    [photoPopView show];
    
}

#pragma mark - 上传图片--------------------------
- (void) imageUpload:(int)numberImg:(UIImage *)imageImage{
   NSString *url = [NSString stringWithFormat:@"http://%@%@",IP_Address_Fresh,SX_uploadDemandSupplyImg];
    //分界线的标识符
    NSString *TWITTERFON_FORM_BOUNDARY = @"AaB03x";
    //根据url初始化request
    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]
                                                           cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                                       timeoutInterval:10];
    //分界线 --AaB03x
    NSString *MPboundary=[[NSString alloc]initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];
    //结束符 AaB03x--
    NSString *endMPboundary=[[NSString alloc]initWithFormat:@"%@--",MPboundary];
    //要上传的图片
    //    UIImage *image=[params objectForKey:@"pic"];
    //得到图片的data
    CGSize newSize = CGSizeMake(80, 80);
    UIGraphicsBeginImageContext(newSize);
    [imageImage drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    NSData* data  = UIImageJPEGRepresentation(newImage, 0.7);
    //http body的字符串
    NSMutableString *body=[[NSMutableString alloc]init];
    //设置HTTPHeader中Content-Type的值
    NSString* content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",TWITTERFON_FORM_BOUNDARY];
    ////添加分界线，换行
    [body appendFormat:@"%@\r\n",MPboundary];
    //声明pic字段，文件名为boris.png
    [body appendFormat:@"Content-Disposition: form-data; name=\"pic\"; filename=\"boris.png\"\r\n"];
    //声明上传文件的格式
    [body appendFormat:@"Content-Type: image/png\r\n\r\n"];
    //    [body appendFormat:@"Content-Type: %@\r\n\r\n",content];
    //声明结束符：--AaB03x--
    NSString *end=[[NSString alloc]initWithFormat:@"\r\n%@",endMPboundary];
    //声明myRequestData，用来放入http body
    NSMutableData *myRequestData=[NSMutableData data];
    //将body字符串转化为UTF8格式的二进制
    [myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
    //将image的data加入
    [myRequestData appendData:data];
    //加入结束符--AaB03x--
    [myRequestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
    NSString *headerUserAgent=@"";
    if ([Common getLoginStatus]) {
        NSString *userName = [[Common getLoginInfo] objectForKey:Key_User_nickname];
        NSString *userId  = [NSString stringWithFormat:@"%@",[[Common getLoginInfo] objectForKey:Key_User_userId]];
        NSString *encryptPwd  = [ [Common getLoginInfo] objectForKey:Key_User_password];
        NSString *localUserIdentify  = [[UIDevice currentDevice].identifierForVendor UUIDString];
        headerUserAgent = [NSString stringWithFormat:@"%@|%@|%@|%@",userName,userId,encryptPwd,localUserIdentify];
    }else{
        headerUserAgent = @"|||";
    }
    
    //设置HTTPHeader
    [request setValue:content forHTTPHeaderField:@"Content-Type"];
    //设置User-Agent
    [request setValue:headerUserAgent forHTTPHeaderField:@"User-Agent"];
    //设置Content-Length
    [request setValue:[NSString stringWithFormat:@"%d", [myRequestData length]] forHTTPHeaderField:@"Content-Length"];
    //设置http body
    [request setHTTPBody:myRequestData];
    //http method
    [request setHTTPMethod:@"POST"];
    
    //建立连接，设置代理
    //    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    //上传文件开始
    NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    //获得返回值
    NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
    
    NSData *jsonData = [returnString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *error = nil;
    NSMutableDictionary *dictionary = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&error];
    
    //取得返回的图片名
    //    NSArray* array = [returnString componentsSeparatedByString:@"###"];
    NSString * image = [NSString stringWithFormat:@"%@", dictionary[@"result"][0][@"simaId"]];
    [_images addObject:image];
    [_photoButton setTitle:[NSString stringWithFormat:@"%ld/5",_images.count] forState:UIControlStateNormal];
}


#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    if (tag==SX_SX_appAddMarketSupply) {
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
             [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:2];
            [self.navigationController  popViewControllerAnimated:YES];
            
        }
    }
}

-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
        //
        [self dismissWaitDialog];
        
        
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
